package org.mespilus.mespilusweb.ui.login.server;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mespilus.mespilusweb.datalayer.PMF;
import org.mespilus.mespilusweb.datalayer.securitymanagement.BCrypt;
import org.mespilus.mespilusweb.datalayer.usermanagement.Member;

public class LoginService extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Member.class);
		query.setFilter("mail == userName");
		query.declareParameters("String userName");

		List<Member> users = (List<Member>) query.execute(request
				.getParameter("userName"));
		if (users.isEmpty()) {
			System.out.println("User does'nt exist.");
			response.sendRedirect(request.getHeader("referer"));
		} else {
			Member user = users.get(0);
			System.out.println("User exist.");
			String password = request.getParameter("passwd");
			boolean valid = BCrypt.checkpw(password, user.getHash());
			if (!valid)
				System.out.println("Bad Passwd.");
			else {
				System.out.println("Login ok");
				response.sendRedirect("/mespilusweb/MainWindow.html");
			}
		}
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
